<template>
  <div>
    <el-card class="search-card">
      <BasicTableForm
        ref="formData"
        resetBtnName="重置"
        isBtnBarSingleRow
        :formColumns="formItemList"
        :dataSource="formData"
        :searchBtnRender="searchBtnRenderFn"
        @getFormData="getFormDataFn"
      />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showSelectCol
        showActionCol
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :pageSizes="pageSizes"
        :tableHeight="480"
        :actionRender="renderTableActionFn"
        :selectionChange="handleTableSelection"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange"
      >
        <div v-show="showBtn('批量提交')" slot="content_context">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-upload2"
            :disabled="tableInfo.selection.length === 0"
            :loading="btnLoading.batchSubmit"
            @click="handleBatchSubmit"
            >批量提交</el-button
          >
        </div>
      </basic-table>
    </el-card>
  </div>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapGetters } from 'vuex';
import BasicTableForm from '@/components/BasicForm';
import BasicTable from '@/components/BasicTable';
import { tableColumns, formItemList } from '../constants/skuToBeSubmit';
import { PRODUCT_TYPES } from '../constants';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
import { judgeAuthDepartmentFn } from '@/pages/commodity/modules/utils';
export default {
  components: {
    BasicTableForm,
    BasicTable
  },
  data () {
    return {
      formItemList: formItemList,
      formData: {
        categoryPath: '',
        spuNo: '',
        productNameFinal: '',
        productType: '',
        createOper: ''
      },
      tableInfo: {
        list: [],
        selection: [],
        columns: tableColumns,
        loading: false
      },
      btnLoading: {
        batchSubmit: false
      },
      pagination: {
        nowPage: 1,
        totalNum: 0,
        pageShow: 10
      },
      pageSizes: [10, 20, 30, 40],
      productTypes: PRODUCT_TYPES,
      apiObj: {
        getProductAddStateList: { // 表格数据请求接口
          url: '/sysback/product/addSku/stateInfo/getProductAddStateList',
          type: 'post'
        },
        batchCreateProductAddSkuRecordInfo: { // 提交接口
          url: '/sysback/product/addSku/recordInfo/batchCreateProductAddSkuRecordInfo',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    this.handleSearch();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  methods: {
    // 表单查询按钮
    searchBtnRenderFn () {
      return (
        <el-button
          type="primary"
          icon="el-icon-search"
          onClick={() => this.handleSearch()}
        >查询</el-button>
      )
    },
    // 获取表单数据
    getFormDataFn (formData) {
      this.formData = formData;
    },
    // 表格操作按钮
    renderTableActionFn (h, { row }) {
      const permissionBtns = [
        { label: '提交', methodFn: this.handleSubmit },
        { label: '删除', methodFn: this.handleToDelete },
      ];
      return (<div class="table-action">
        {permissionBtns.map(item => {
          if (this.showBtn(item.label)) {
            return <el-button
              type="text"
              onClick={() => item.methodFn(row)}
            >{item.label}</el-button>
          }
        })}
      </div>);
    },
    // 删除
    handleToDelete (row) {
      this.$confirm('删除后将把该商品的所有完善信息删除，您确认吗？', '删除', {
        type: 'warning',
      }).then(() => {
        sessionStorage.setItem('buttonId', getBtnsId('删除'));
        this.deleteRecord(row.productUuid, row.spuNo);
      }).catch(() => {});
    },
    // 删除单据
    async deleteRecord (uuid, spuNo) {
      try {
        const url = `/sysback/product/addSku/stateInfo/deleteByProductuuid?uuid=${uuid}&spuNo=${spuNo}`
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, 'post');
        this.tableInfo.loading = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('删除成功');
          this.getTableDataFn();
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 查询表单
    handleSearch () {
      const curBtnId = getBtnsId('查询');
      sessionStorage.setItem('buttonId', curBtnId);
      this.pagination.nowPage = 1;
      this.getTableDataFn();
    },
    // 获取表格数据
    async getTableDataFn () {
      const data = {
        groupFlag: 1, // * 是否是集团总部 0:不是 1:是
        queryType: 2, // 查询类型 1 待完善 2 待提交 3 待审核 4 审核驳回
        ...this.formData,
        nowPage: this.pagination.nowPage,
        pageShow: this.pagination.pageShow,
      }
      const { url, type } = this.apiObj.getProductAddStateList;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, false);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          const { results, totalNum } = res.retData;
          this.tableInfo.list = results || [];
          this.pagination.totalNum = totalNum;
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 重置表单
    handleReset () {
      this.$refs.formData.handleResetForm();
    },
    // 页码切换
    handlePageChange (val) {
      this.pagination.nowPage = val;
      this.getTableDataFn();
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.pagination.pageShow = val;
      this.getTableDataFn();
    },
    handleTableSelection (list) {
      this.tableInfo.selection = list;
    },
    // 提交
    async handleSubmit (row) {
      const flag = judgeAuthDepartmentFn([row]); // 验归属部门方法
      if (!flag) {
        return false;
      }
      const data = [row.productUuid];
      const { url, type } = this.apiObj.batchCreateProductAddSkuRecordInfo;
      sessionStorage.setItem('buttonId', getBtnsId('提交'));
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data);
        this.tableInfo.loading = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('提交成功');
          this.getTableDataFn();
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 批量提交
    handleBatchSubmit () {
      const flag = judgeAuthDepartmentFn(this.tableInfo.selection); // 验归属部门方法
      if (!flag) {
        return false;
      }
      const { url, type } = this.apiObj.batchCreateProductAddSkuRecordInfo;
      const data = this.tableInfo.selection.map(row => row.productUuid);
      const title = '批量操作';
      const content = '确定批量提交吗？';
      this.tableInfo.loading = true;
      this.btnLoading.batchSubmit = true;
      this.$confirm(content, title, {
        type: 'warning'
      }).then(async () => {
        sessionStorage.setItem('buttonId', getBtnsId('批量提交'));
        const res = await ApiRequest(url, type, data);
        this.tableInfo.loading = false;
        this.btnLoading.batchSubmit = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('批量提交成功');
          this.getTableDataFn();
        }
      }).catch(() => {
        this.tableInfo.loading = false;
        this.btnLoading.batchSubmit = false;
      });
    },
  }
}
</script>
<style lang="less" scoped>
.el-select-wrap {
  width: 100%;
}
</style>
